//
//  InvitationWebViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2019/2/18.
//  Copyright © 2019年 张庆勇. All rights reserved.
//

#import "InvitationWebViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import "InvitationAlearView.h"
static NSString * identiy_callback  = @"SavePictures";
@interface InvitationWebViewController ()<UIWebViewDelegate,WKNavigationDelegate,UIGestureRecognizerDelegate,WKScriptMessageHandler, WKUIDelegate>
@property (nonatomic, strong) WKWebView *wk_WebView;
@property (nonatomic, strong) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *closeBarButtonItem;
@property (nonatomic, strong) id <UIGestureRecognizerDelegate>delegate;
@property (nonatomic, strong) UIRefreshControl *refreshControl;
@property (nonatomic, strong) UIProgressView *loadingProgressView;
@property (nonatomic, strong) UIButton *reloadButton;
@property (nonatomic, strong) UIButton *blakButton;

@end

@implementation InvitationWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createWebView];
    [self createNaviItem];
    [self loadRequest];
}

#pragma mark 版本适配
- (void)createWebView {
    self.view.backgroundColor = TABLEVIEWLCOLOR;
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.reloadButton];
    [self.view addSubview:self.wk_WebView];
    [self.view addSubview:self.loadingProgressView];
}
- (WKWebView *)wk_WebView {
    if (_wk_WebView == nil) {
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [WKUserContentController new];
        [configuration.userContentController addScriptMessageHandler:self name:@"SavePictures"];
     
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"token"] = [EXUserManager userInfo].token;
        dic[@"rate"] = [EXUserManager getValuationMethod];
        dic[@"lang"] = [ZBLocalized sharedInstance].currentLanguage;
        NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:(NSJSONWritingPrettyPrinted) error:nil];
        
        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSString *js = [NSString stringWithFormat:@"window.getUserToken = %@", jsonStr];
        
        WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES];
        [configuration.userContentController addUserScript:script];
        // 显示WKWebView
        _wk_WebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - kStatusBarAndNavigationBarHeight) configuration:configuration];
        _wk_WebView.navigationDelegate = self;
        _wk_WebView.backgroundColor = TABLEVIEWLCOLOR;
        _wk_WebView.UIDelegate = self; // 设置WKUIDelegate代理
        //添加此属性可触发侧滑返回上一网页与下一网页操作
        _wk_WebView.allowsBackForwardNavigationGestures = YES;
        if (@available(iOS 11.0, *)){
            _wk_WebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        //进度监听
        [_wk_WebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _wk_WebView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        _loadingProgressView.progress = [change[@"new"] floatValue];
        WeakSelf
        if (_loadingProgressView.progress == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.loadingProgressView.hidden = YES;
            });
        }
    }
}

- (void)dealloc {
    [_wk_WebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_wk_WebView stopLoading];
    _wk_WebView.UIDelegate = nil;
    _wk_WebView.navigationDelegate = nil;
    //    [_wk_WebView.configuration.userContentController removeScriptMessageHandlerForName:identiy_callback];
}

- (UIProgressView*)loadingProgressView {
    if (!_loadingProgressView) {
        _loadingProgressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 2)];
        _loadingProgressView.progressTintColor = TABTITLECOLOR;
        _loadingProgressView.backgroundColor = MAINBLACKCOLOR;
    }
    return _loadingProgressView;
}

- (UIRefreshControl*)refreshControl {
    if (!_refreshControl) {
        _refreshControl = [[UIRefreshControl alloc]init];
        [_refreshControl addTarget:self action:@selector(webViewReload) forControlEvents:UIControlEventValueChanged];
    }
    return _refreshControl;
}
- (void)webViewReload {
    [_wk_WebView reload];
}
- (UIButton*)reloadButton {
    if (!_reloadButton) {
        _reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _reloadButton.frame = CGRectMake(0, 0, 150, 150);
        _reloadButton.center = self.view.center;
        _reloadButton.layer.cornerRadius = 75.0;
        [_reloadButton setBackgroundImage:[UIImage imageNamed:@"placeholder"] forState:UIControlStateNormal];
        [_reloadButton setTitle:@"无效地址" forState:UIControlStateNormal];
        
        [_reloadButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_reloadButton setTitleEdgeInsets:UIEdgeInsetsMake(200, -50, 0, -50)];
        _reloadButton.titleLabel.numberOfLines = 0;
        _reloadButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        CGRect rect = _reloadButton.frame;
        rect.origin.y -= 100;
        _reloadButton.frame = rect;
        _reloadButton.enabled = NO;
    }
    return _reloadButton;
}
#pragma mark 导航按钮
- (void)createNaviItem {
    [self showLeftBarButtonItem];
    [self showRightBarButtonItem];
}
- (void)showLeftBarButtonItem {
    if ([_wk_WebView canGoBack]) {
        [self.view addSubview:self.blakButton];
    } else {
        self.navigationItem.leftBarButtonItem = self.backBarButtonItem;
        
        [self.view addSubview:self.blakButton];
    }
}
- (UIBarButtonItem *)backBarButtonItem
{
    
    UIButton * Barbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Barbutton.frame = CGRectMake(-20, 0, 50, 30);
    Barbutton.titleLabel.font = AutoFont(13);
    [Barbutton setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].backicon] forState:UIControlStateNormal];
    
    
    [Barbutton setTitleColor:RGBA(114, 145, 161, 1) forState:UIControlStateNormal];
    [Barbutton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    Barbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //    [Barbutton sizeToFit];
    [Barbutton setEnlargeEdgeWithTop:60 right:60 bottom:60 left:60];
    UIBarButtonItem * item = [[UIBarButtonItem alloc]initWithCustomView:Barbutton];
    return item;
}
- (void)showRightBarButtonItem {
    
}
- (UIButton *)blakButton
{
    if (!_blakButton) {
        _blakButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 80, 49)];
        [_blakButton addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
        [_blakButton setEnlargeEdgeWithTop:60 right:60 bottom:60 left:60];
    }
    return _blakButton;
}
- (void)back:(UIButton*)item {
    if ([_wk_WebView canGoBack]) {
        //        [_webView goBack];
        //        [_wk_WebView goBack];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark 自定义导航按钮支持侧滑手势处理
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    if (self.navigationController.viewControllers.count > 1) {
        self.delegate = self.navigationController.interactivePopGestureRecognizer.delegate;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
        
        
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = self.delegate;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}
#pragma mark 加载请求
- (void)loadRequest {
    
    if (![self.urlStr hasPrefix:@"http"]) {//是否具有http前缀
        self.urlStr = [NSString stringWithFormat:@"http://%@",self.urlStr];
    }
  
     [_wk_WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
}

#pragma mark WebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    webView.hidden = NO;
    // 不加载空白网址
    if ([request.URL.scheme isEqual:@"about"]) {
        webView.hidden = YES;
        return NO;
    }
    
    return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //导航栏配置
    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self showLeftBarButtonItem];
    [_refreshControl endRefreshing];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    webView.hidden = YES;
}
#pragma mark WKNavigationDelegate

#pragma mark 加载状态回调

//页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    webView.hidden = NO;
    _loadingProgressView.hidden = NO;
    
    if ([webView.URL.scheme isEqual:@"about"]) {
        webView.hidden = YES;
    }
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"方法名:%@", message.name);
    NSLog(@"参数:%@", message.body);
    NSDictionary * dic = message.body;
    NSArray * urls = dic[@"link"];
    NSString * url =@"";
    if (![NSString isEmptyString:urls[0]])
    {
        url = urls[0];
    }
    InvitationAlearView *  AlearView = [[InvitationAlearView alloc]initWithimageurl:dic[@"image"] titleStr:@"保存到相册" QRcodWithUrl:url SaveBlock:^{
        
    }];
    AlearView.animationStyle = LXASAnimationTopShake;
    [AlearView showLXAlertView];
    
}
//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    //导航栏配置
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        self.navigationItem.title = title;
    }];
   

    [self showLeftBarButtonItem];

    [_refreshControl endRefreshing];
}
- (NSString *)noWhiteSpaceString:(NSString *)newString {
    //去除掉首尾的空白字符和换行字符
    newString = [newString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    newString = [newString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符使用
    newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    可以去掉空格，注意此时生成的strUrl是autorelease属性的，所以不必对strUrl进行release操作！
    return newString;
}
//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    webView.hidden = YES;
}

//HTTPS认证
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    // 判断服务器采用的验证方法
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        // 如果没有错误的情况下 创建一个凭证，并使用证书
        if (challenge.previousFailureCount == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        }else {
            // 验证失败，取消本次验证
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    }else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        
    }
    
}


@end
